package com.kfm.spring.proxy;

import com.kfm.spring.service.AccountService;
import com.kfm.spring.service.IAccountService;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ServiceProxy {

    public static void main(String[] args) {
        AccountService accountService = new AccountService();

//        accountService.transfer("a", "b", 100);

        IAccountService proxy = (IAccountService) Proxy.newProxyInstance(accountService.getClass().getClassLoader(),
                accountService.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        try{
                            System.out.println("开启事务");
                            // 执行方法, 相当于 accountService.transfer(args);
                            Object obj = method.invoke(accountService, args);

                            System.out.println("提交事务");
                            return obj;
                        } catch (Exception ex){
                            System.out.println("回滚事务");
                        }
                        return null;
                    }
                }
        );

        proxy.transfer("a", "b", 100);

        proxy.get();
    }
}
